<script setup lang="ts">
import {type ECharts, type EChartsOption, init} from 'echarts';
import {ref, watch, onMounted, onBeforeUnmount} from 'vue';
import {userStore} from "../../store";

const store = userStore();

// 定义props
interface Props {
    width?: string;
    height?: string;
    option: EChartsOption | Object;
    refresh: boolean;
}

const props = withDefaults(defineProps<Props>(), {
    width: '100%',
    height: '100%',
    refresh: true,
    option: () => ({})
});

const chartRef = ref<HTMLDivElement>();
let chart: ECharts;
// eslint-disable-next-line no-undef
let timer: number | undefined | NodeJS.Timeout;

// 初始化echarts
const initChart = (): void => {
    if (chart !== undefined) {
        chart.dispose();
    }
    chart = init(chartRef.value as HTMLDivElement, store.isDarkMode ? 'dark' : 'light');
    // 拿到option配置项，渲染echarts
    chart?.setOption(props.option as EChartsOption, false, false);
};

// 重新渲染echarts
const resizeChart = (): void => {
    timer = setTimeout(() => {
        if (chart) {
            chart.resize();
        }
    }, 2100);
};

onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeChart);
});

onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeChart);
    clearTimeout(timer);
    timer = 0;
});

watch(() => [props.option, store.isDarkMode, store.isFullScreen], () => {
        initChart();
    }, {deep: true}
);

</script>

<template>
    <div ref="chartRef" :style="{ height: height, width: width }" />
</template>
